<template>
  <div v-if="isPipeBrustShow" class="componentContainer" v-drag>
    <el-dialog
      style="width: 50%"
      :modal="false"
      :visible.sync="isPipeBrustShow"
      :close-on-click-modal="false"
    >
      <template #title>
        <div
          class="custom-header drag-handle"
          style="font-size: 1rem; display: flex"
        >
          <div
            class="bar"
            style="
              width: 5px;
              height: 20px;
              background-color: white;
              margin-right: 10px;
            "
          ></div>
          <span>缓冲区分析</span>
        </div>
      </template>
      <div
        style="
          margin-top: -20px;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          height: 180px;
        "
      >
        <div>
          <span style="color: #fff; font-size: 16px">选择分析图层:</span>
          <el-select
            v-model="analysisLayer"
            placeholder="请选择"
            style="margin-left: 15px"
            @change="selectChange"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div>
          <span style="color: #fff; font-size: 16px">分析半径：</span>
          <el-input
            style="width: 48%; margin-left: 15px"
            v-model="analysisRadius"
            placeholder="请输入"
          ></el-input>
          <span style="color: #fff; font-size: 16px; margin-left: 5px">米</span>
        </div>
        <div class="operateFeature">
          <div class="item" @click="drawOperate('point')">
            <span>选择分析要素</span>
            <img :src="bufferImg.point" alt="" />
          </div>
          <!-- <div class="item" @click="drawOperate('line')">
            <span>线</span>
            <img :src="bufferImg.line" alt="" />
          </div>
          <div class="item" @click="drawOperate('area')">
            <span>面</span>
            <img :src="bufferImg.area" alt="" />
          </div> -->
        </div>
        <div style="display: flex; justify-content: center">
          <el-button
            style="margin-right: 20px"
            type="primary"
            plain
            @click="reset"
            >重置</el-button
          >
          <el-button type="primary" plain @click="bufferAnalysis"
            >分析</el-button
          >
        </div>
      </div>
      <div class="calResult">
        <span>分析结果：</span>
        <span>{{ analysisLayerName }}共有：{{ calResultNum }}</span
        ><span>个</span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dmgis from "@/api/dmgis";
import { getChineseByEnglish } from "@/api/EquipmentManagement.js";
import { feature } from "@turf/turf";
export default {
  components: {},
  data() {
    return {
      lineLayer: null,
      analysisLayerName: "",
      calResultNum: 0,
      querySpatialLayer: null,
      projectLayer: null,
      bufferLayer: null,
      bufferImg: {
        point: require("@/assets/point.png"),
        line: require("@/assets/line.png"),
        area: require("@/assets/area.png"),
      },
      operateFeatureItem: "",
      connectivityTableData: [],
      isPipeBrustShow: this.dialogVisible, // 初始化为从父组件传来的值
      analysisRadius: 10,
      analysisLayer: "",
      queryFeatureData: null,
      options: [],
      value: "",
      map: null,
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    selectChange(data) {
      this.analysisLayerName = "";
      let node = data.split("_");
      let result = node.slice(0, 2).join("_");
      getChineseByEnglish([result]).then((res) => {
        this.analysisLayerName = res.data[result];
      });
    },
    async initData() {
      this.map = this.$store.getters.Map;
      this.projectLayer = this.$store.getters.projectLayer;
      this.bufferLayer = this.map.layer.createVectorLayer("bufferLayer");
      this.querySpatialLayer =
        this.map.layer.createVectorLayer("空间查询点图层");
      this.lineLayer = this.map.layer.createVectorLayer("空间查询线图层", {}, 2);
      let layersAttribute = this.$store.state.layersAttribute;
      if (layersAttribute.length == 0) {
        this.$message.warning("请先获取服务图层");
        return;
      }

      let cnNamewGroup = {};
      await getChineseByEnglish(layersAttribute).then((res) => {
        console.log(res, "res");
        cnNamewGroup = res.data;
        this.options = layersAttribute.map((item) => {
          return {
            label: cnNamewGroup[item],
            value: item,
          };
        });
      });
    },
    reset() {
      this.analysisRadius = 10;
      this.analysisLayer = "";
    },
    drawOperate(type) {
      if (this.operateFeatureItem == type) {
        this.map.interaction.cancelYjDraw();
        this.operateFeatureItem = "";
        this.bufferImg[type] = require(`@/assets/${type}.png`);
      } else {
        (this.bufferImg.point = require("@/assets/point.png")),
          (this.bufferImg.line = require("@/assets/line.png")),
          (this.bufferImg.area = require("@/assets/area.png"));
        this.operateFeatureItem = type;
        this.bufferImg[type] = require(`@/assets/${type}-active.png`);
        this.map.interaction.addAreaDraw("Point", 1);
      }
    },
    async bufferAnalysis() {
      this.querySpatialLayer.getSource().clear();
      if (!this.analysisLayer) {
        this.$message.warning("请选择分析图层");
        return;
      }
      //获取绘制要素地物id
      let featureParams = this.getGeom.getCoordinates();
      let featureId = "";
      if (!featureParams) {
        this.$message.warning("请先绘制分析要素");
        return;
      }
      let getFeatureParams = new dmgis.object.FeatureServiceParam(
        "TapWaterMap"
      );
      let SpatialQuery = new dmgis.object.SpatialQuery();
      if (this.operateFeatureItem == "point") {
        var rect = new dmgis.object.Envelope();
        rect.minx = featureParams[0] - 10;
        rect.miny = featureParams[1] - 10;
        rect.maxx = featureParams[0] + 10;
        rect.maxy = featureParams[1] + 10;
        SpatialQuery.env = rect; //矩形
        getFeatureParams.sql = SpatialQuery;

        let layersAttribute = this.$store.state.layersAttribute;
        if (layersAttribute.length == 0) {
          this.$message.warning("请先获取服务图层");
          return;
        }
        getFeatureParams.strlayername = this.analysisLayer;
        await this.projectLayer
          .SendFeatureMapService(getFeatureParams)
          .then((res) => {
            let featureObj = res.objset;
            if (!featureObj) {
              this.$message.warning("查询要素失败");
              return;
            }
            featureId = featureObj[0].id;
            // let featureObj = this.$store.getters.dmGetFeature.objset;
            // if (!featureObj) {
            //   this.$message.warning("查询要素失败");
            //   return;
            // }
            // featureId = featureObj[0].id;
          });
      }

      //调用buffer缓冲区服务
      let getBufferParams = new dmgis.object.BufferServiceParam(
        "TapWaterMap",
        this.analysisLayer
      );
      getBufferParams.blc = Number(this.analysisRadius);
      getBufferParams.no = featureId - 1;
      // ;

      await this.projectLayer.SendBufferMapService(getBufferParams).then(() => {});
        let bufferResult = this.$store.getters.dmGetBuffer;
        console.log(bufferResult, "缓冲区结果");
        this.bufferLayer.getSource().clear();
        this.lineLayer.getSource().clear();
        if (bufferResult.strPos) {
          let coorGroup = bufferResult.strPos.split(";");
          const coordArray = [];
          coorGroup.forEach((pair) => {
            const [x, y] = pair.trim().split(" ");
            coordArray.push([parseFloat(x), parseFloat(y)]);
          });

          // ;
          this.map.layer.addPolygonsToLayer(this.bufferLayer, [coordArray], {
            fill: "rgba(255, 255, 255, 0.5)",
            strokeColor: "#000",
            strokeWidth: 2,
          });
          //加点缓冲区的其他地物结果
          if (coordArray.length > 0) {
            let areaPos = "";
            coordArray.forEach((item, index) => {
              let itemGroup = item.join(" ");
              if (index == coordArray.length - 1) {
                areaPos += itemGroup;
              } else {
                areaPos += itemGroup + ";";
              }
            });
            let getFeatureParams = new dmgis.object.FeatureServiceParam(
              "TapWaterMap"
            );
            let SpatialQuery = new dmgis.object.SpatialQuery();
            SpatialQuery.strPos = areaPos;
            getFeatureParams.sql = SpatialQuery;
            getFeatureParams.strlayername = this.analysisLayer;
            this.projectLayer
              .SendFeatureMapService(getFeatureParams)
              .then((res) => {
                let featureObj = res.objset;
                console.log(featureObj, "查询多要素");

                // let featureObj = this.$store.getters.dmGetFeature.objset;
                if (!featureObj) {
                  this.$message.warning("查询多要素失败");
                  return;
                }

                let dataObjectgroup = [];
                let strCor = [];
                // this.querySpatialLayer.getSource().clear();
                featureObj.forEach((item) => {
                  let dataObject = {};
                  if (item.strCor) {
                    let coords = item.strCor.split(";");
                    coords.forEach((item) => {
                      strCor.push(item.split(" "));
                    });
                  }
                  item.rec.forEach((data) => {
                    dataObject[data.fldname] = data.fldval;
                  });
                  dataObjectgroup.push(dataObject);
                });

                this.calResultNum = dataObjectgroup.length;
                //加点
                dataObjectgroup.forEach((item) => {
                  if (item.x_coord && item.y_coord) {
                    this.map.marker.addMarker(
                      Number(item.x_coord.replace(/\s+/g, "")),
                      Number(item.y_coord.replace(/\s+/g, "")),
                      this.querySpatialLayer,
                      {
                        scale: 1.5, //大小
                        radius: 5,
                        pBorderColor: "#000000",
                        pBorderWidth: 1,
                        pFillColor: "green",
                      },
                      item
                    );
                  }
                });
                //加线
                if (strCor.length > 0) {
                  console.log(strCor, "strCor");

                  strCor.forEach((item, index) => {
                    let flag = index + 1;
                    if (flag % 2 == 0) {
                      this.map.marker.addLineString(
                        strCor[flag - 2],
                        strCor[flag - 1],
                        this.lineLayer,
                        {
                          color: "green",
                          width: 6,
                        },
                        "",
                        ""
                      );
                    }
                  });
                }
              });
          }
        }
      
    },
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
  },
  watch: {
    dialogVisible(newVal) {
      this.isPipeBrustShow = newVal;
    },
    operateFeatureItem(newVal) {},
    getGeom(newVal) {},
  },
  computed: {
    getGeom() {
      return this.$store.state.geom;
    },
  },
  beforeDestroy() {
    if (this.map) {
      this.map.map.removeLayer(this.bufferLayer);
      this.map.map.removeLayer(this.querySpatialLayer);
      this.map.map.removeLayer(this.lineLayer);
      this.map.interaction.cancelYjDraw();
    }
  },
};
</script>

<style lang="scss" scoped>
.operateFeature {
  display: flex;
  align-items: center;
  height: 20%;
  width: 100%;
  font-size: 0.8rem;
  color: #fff;
  justify-content: space-around;
  .item {
    display: flex;
    img {
      cursor: pointer;
      height: 1.5rem;
      margin: 0 0.5rem;
    }
  }
}
.componentContainer {
  pointer-events: none;
  position: absolute;
  width: 50rem;
  height: 50rem;
  top: 0;
  left: -16vw;
  ::v-deep .el-dialog {
    pointer-events: auto;
  }
  ::v-deep .el-dialog__header {
    text-align: left;
  }
}
::v-deep .el-dialog__wrapper {
  position: absolute !important;
  width: 50rem !important;
}
::v-deep .el-dialog {
  background-color: #285383;
  .el-dialog__title {
    color: white;
  }
}
.calResult {
  width: 100%;
  /* height: 50rem; */
  color: #ccc;
}
</style>
